<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import { NButton, NForm, NFormItem, NInput, NInputNumber, NPopconfirm, NTreeSelect, NTag } from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'

import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '属性管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
    modalVisible,
    modalTitle,
    modalLoading,
    handleSave,
    modalForm,
    modalFormRef,
    handleEdit,
    handleDelete,
    handleAdd,
} = useCRUD({
    name: '商品属性',
    initForm: {},
    doCreate: api.creategoodsAttribute,
    doUpdate: api.updategoodsAttribute,
    doDelete: api.deletegoodsAttribute,
    refresh: () => $table.value?.handlerefresh(),
})
const deptOption = ref([])
const isDisabled = ref(false)
const data = reactive({
    attributeOption: [{
        id: 1,
        name: '描述属性'
    },
    {
        id: 2,
        name: '规格属性'
    },
    ]
});


onMounted(() => {
    $table.value?.handleSearch()
    // api.getCategory().then((res) => (deptOption.value = res.data))
    //   api.getgoodsCategoryTree().then((res) => (deptOption.value = res.data))
})

const validateAddUser = {
    name: [
        {
            required: true,
            message: '请输入属性名称',
            trigger: ['input', 'blur', 'change'],
        },
    ],
}

async function addDepts() {
    isDisabled.value = false
    handleAdd()
}

const columns = [
    {
        title: 'ID',
        key: 'id',
        width: 60,
        align: 'center',
        ellipsis: { tooltip: true },
    },
    {
        title: '属性名',
        key: 'name',
        width: 'auto',
        align: 'center',
        ellipsis: { tooltip: true },
    },
    {
        title: '属性类型',
        key: 'type',
        width: 100,
        align: 'center',
        render(row) {
            return h(
                NTag,
                { type: 'primary', size: "small", bordered: false, style: { margin: '2px 3px' } },
                { default: () => (row.type==1 ? '描述属性' : '规格属性') }
            )
        },
    },
    {
        title: '属性值',
        key: 'tags',
        align: 'center',
        width: 'auto',
        render(row) {
            const roles = row.tags ?? []
            const group = []
            for (let i = 0; i < roles.length; i++)
                group.push(
                    h(NTag, { type: 'primary', size: "small", bordered: false, style: { margin: '2px 3px' } }, { default: () => roles[i] })
                )
            return h('span', group)
        }
    },
    {
        title: '操作',
        key: 'actions',
        width: 'auto',
        align: 'center',
        fixed: 'right',
        render(row) {
            return [
                withDirectives(
                    h(
                        NButton,
                        {
                            size: 'small',
                            type: 'primary',
                            style: 'margin-right: 8px;',
                            onClick: () => {
                                console.log('row', row.parent_id)
                                if (row.parent_id === 0) {
                                    isDisabled.value = true
                                } else {
                                    isDisabled.value = false
                                }
                                handleEdit(row)
                            },
                        },
                        {
                            default: () => '编辑',
                            icon: renderIcon('material-symbols:edit', { size: 16 }),
                        }
                    ),
                    [[vPermission, 'post/api/content/category/update']]
                ),
                h(
                    NPopconfirm,
                    {
                        onPositiveClick: () => handleDelete({ data_id: row.id }, false),
                        onNegativeClick: () => { },
                    },
                    {
                        trigger: () =>
                            withDirectives(
                                h(
                                    NButton,
                                    {
                                        size: 'small',
                                        type: 'error',
                                    },
                                    {
                                        default: () => '删除',
                                        icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                                    }
                                ),
                                [[vPermission, 'delete/api/content/category/delete']]
                            ),
                        default: () => h('div', {}, '确定删除该分类吗?'),
                    }
                ),
            ]
        },
    },
]
</script>

<template>
    <!-- 业务页面 -->
    <CommonPage show-footer title="属性管理列表">
        <template #action>
            <div>
                <NButton v-permission="'post/api/content/category/create'" class="float-right mr-15" type="primary"
                    @click="addDepts">
                    <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建属性
                </NButton>
            </div>
        </template>
        <!-- 表格 -->
        <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getgoodsAttribute">
            <template #queryBar>
                <QueryBarItem label="属性名称" :label-width="80">
                    <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入属性名称"
                        @keypress.enter="$table?.handleSearch()" />
                </QueryBarItem>
            </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave">
            <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm"
                :rules="validateAddUser">
                <NFormItem label="属性名" path="name">
                    <NInput v-model:value="modalForm.name" clearable placeholder="请输入属性名称" />
                </NFormItem>
                <NFormItem label="属性类型" path="type">
                    <n-radio-group v-model:value="modalForm.type" name="radiogroup" :default-value="1">
                      <n-space>
                        <n-radio v-for="item in data.attributeOption" :key="item.id" :value="item.id">
                          {{ item.name }}
                        </n-radio>
                      </n-space>
                    </n-radio-group>
                </NFormItem>
                <NFormItem label="属性值" path="tags">
                    <n-dynamic-tags v-model:value="modalForm.tags" />
                </NFormItem>
            </NForm>
        </CrudModal>
    </CommonPage>
</template>
